#include "GameUtils.h"
#include "Texture.h"
#include "Rect.h"
#include "Utils.h"

#ifdef ANDROID
#include "libzip/zip.h"
#include "ApkLoader.h"
#include "string.h"
#include "stdlib.h"
#endif

void DrawNumber(Texture* tex, int spriteWidth, int spriteHeight,
							  int number,float x,float y,float zoomX,float zoomY, float alpha)
{
	int temp;
	Rect *rSrc=new Rect(0, 0, spriteWidth, spriteHeight);
	do
	{
		temp=number%10;
		number=number/10;
		rSrc->x = spriteWidth*temp;
		tex->Render(x, y, rSrc, zoomX, zoomY, 0, alpha, 1.0);
		x-=spriteWidth*zoomX;
	}while(number>0);
}

bool IsPointInRect(int x, int y, Rect* rect)
{
	return (x > rect->x && x < rect->x + rect->width
		&& y>rect->y && y < rect->y + rect->height);
}

void Swap(int* a, int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}

void ReadTxtToLine(const char* fileName, vector<char*> *lines)
{
	//WIN32
#ifdef WIN32

	FILE* file = 0;
	int fileLength;
	char* buffer = 0;
 
	file = fopen(fileName, "rb");

	if(file == 0)
	{
		PRINT("Cannot read file\n");
		return;
	}

	//get file length
	fseek(file, 0, SEEK_END);
	fileLength = ftell(file);
	fseek(file, 0, SEEK_SET);

	buffer = (char*) malloc(fileLength + 1);
	if(buffer == 0)
	{
		printf("Cannot allocate memory\n");
		return;
	}

	fread(buffer, fileLength, 1, file);
	buffer[fileLength] = '\0';

	fclose(file);

#elif ANDROID
	zip_file *file = 0;
	int fileLength;
	char* buffer = 0;

	file = zip_fopen(ApkLoader::GetInstance()->GetApkFile(), fileName, 0);

	if(file == 0)
	{
		PRINT("Cannot read file from APK\n");
		return;
	}

	//get length
	struct zip_stat zipInfo;
	zip_stat(ApkLoader::GetInstance()->GetApkFile(), fileName,0, &zipInfo);
	fileLength = zipInfo.size;

	buffer = (char*) malloc(fileLength + 1);
	if(buffer == 0)
	{
		printf("Cannot allocate memory\n");
		return;
	}

	zip_fread(file, buffer, fileLength);
	buffer[fileLength] = '\0';

	zip_fclose(file);

#endif

	char* subStr;
	bool isFirstTime = true;
	while(true)
	{
		if(isFirstTime)
		{
			subStr = strtok(buffer, "\r\n");
			isFirstTime = false;
		}
		else subStr = strtok(NULL, "\r\n");

		if(subStr == 0) break;

		char *line = new char[50];
		strcpy(line, subStr);
		lines->push_back(line);
	}

	free(buffer);
}